// pages/card/applycard/applycard.js
import Toast from '@vant/weapp/toast/toast';
import Notify from '@vant/weapp/notify/notify';
import { cardApplyStat } from '../../../../common/enums';
var { generateUUID } = require('../../../../utils/uuid');
var { getFileExtension } = require('../../../../utils/file');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: getApp().globalData.CustomBar,
    scrollHeight: '100vh',
    active: "1",
    cardInfo: {
      cardId: null,
      name: null,
      count: 1,
      memo: "",
      imgUrlList: [],
    },
    showCardType: false,
    cardTypeColumns: [],
    cardTypeMap: new Map(),
    isQryNextPage: true,
    qryParam: {
      qryUserId: getApp().globalData.userInfo.userId,
      status: -1,
      current: 1,
      size: 10,
    },
    cardApplyList: [],
    currStat: -1,
    fileList: [],
  },
  getScrollHeight() {
    // 获取内容区域的高度
    wx.createSelectorQuery().selectViewport().scrollOffset((res) => {
      this.setData({ scrollHeight: res.scrollHeight + 'px' });
    }).exec()
  },
  onScrollToLower() {
    if (this.data.isQryNextPage && this.data.active == "2") {
      this.qryCardApplyList(true)
    }
  },
  onScroll(event) {
    let isScrollEnd = false;
    if (event.detail.scrollTop > 10) {
      isScrollEnd = true;
    }
    if (isScrollEnd != this.data.isScrollEnd) {
      this.setData({ isScrollEnd: isScrollEnd })
    }
    this.setData({ scrollTop: event.detail.scrollTop });
  },
  onClearCard() {
    this.setData({
      cardInfo: {
        cardId: null,
        name: null,
        count: 1,
        memo: "",
        imgUrlList: [],
      },
      showCardType: false,
      cardTypeColumns: [],
      cardTypeMap: new Map(),
      fileList: [],
    })
  },
  // 过滤标签更新
  onChangeCurrStat(event) {
    const currStat = event.currentTarget.dataset.operation;
    this.setData({ currStat: currStat, 'qryParam.status': currStat, isQryNextPage: true });
    this.qryCardApplyList();
  },
  // Tab页变动
  onChangeTab(event) {
    this.setData({ active: event.detail.name })
    if (event.detail.name == "2") {
      this.qryCardApplyList();
    } else {
      this.setData({ scrollHeight: '100vh' });
    }
  },
  // 展示卡片类型选择器
  onShowCardType() {
    this.setData({ showCardType: true });
    this.qryCardTypeList();
  },
  // 确认选择卡片类型
  onConfirmCardType(event) {
    this.setData({ showCardType: false });
    this.setData({ 'cardInfo.name': event.detail.value });
    this.setData({ 'cardInfo.cardId': this.data.cardTypeMap.get(event.detail.value) });
  },
  // 关闭卡片类型选择器
  onCloseCardType() {
    this.setData({ showCardType: false });
  },
  // 卡片数量
  onBlurToUpdCardCount(event) {
    this.setData({ 'cardInfo.count': event.detail.value })
  },
  // 卡片备注
  onBlurToUpdCardMemo(event) {
    this.setData({ 'cardInfo.memo': event.detail.value })
  },
  // 查询卡片类型列表
  qryCardTypeList() {
    const param = {
      applyFlag: 1
    }
    getApp().callContainer('/api/store/card/list', param, (res) => {
      if (res.data.data) {
        const cardTypeColumns = [];
        const cardTypeMap = new Map();
        for (const cardType of res.data.data.cardList) {
          cardTypeColumns.push(cardType.name);
          cardTypeMap.set(cardType.name, cardType.cardId);
        }
        this.setData({ cardTypeColumns: cardTypeColumns, cardTypeMap: cardTypeMap });
      }
    });
  },
  // 文件选择后
  afterRead(event) {
    const fileList = event.detail.file;
    // 组装文件前缀
    for (const file of fileList) {
      const currDate = new Date().toLocaleDateString().replaceAll('/', '-');
      const userId = getApp().globalData.userInfo.userId;
      const filePath = 'card_apply_picture/' + currDate + '/' + userId + '/';
      const fileName = generateUUID() + '.' + getFileExtension(file.url);
      file.fileName = filePath + fileName;
    }
    // 调用文件上传接口
    const uploadTasks = fileList.map((file) => getApp().uploadFilePromise(file.fileName, file.url));
    Promise.all(uploadTasks)
      .then(data => {
        if (data && data.length > 0) {
          for (const item of data) {
            this.data.fileList.push({ url: item.fileID });
          }
          Toast('上传成功');
          this.setData({ fileList: this.data.fileList });
          setTimeout(() => {
            this.getScrollHeight();
          }, 1000)
        }
      })
      .catch(e => {
        Toast('上传失败');
        console.log(e);
      });
  },
  // 删除图片
  deleteFile(event) {
    this.data.fileList.splice(event.detail.index, 1);
    this.setData({ fileList: this.data.fileList });
    this.getScrollHeight();
  },
  // 提交
  onClickToSubmit() {
    if (!this.data.cardInfo.cardId) {
      Toast('请选择卡片类型！');
      return;
    }
    if (!this.data.cardInfo.count) {
      Toast('请输入卡片数量！');
      return;
    }
    if (!this.data.fileList || this.data.fileList.length == 0) {
      Toast('请上传申请凭证！');
      return;
    }
    const cardInfo = this.data.cardInfo;
    const imgUrlList = [];
    for (const file of this.data.fileList) {
      imgUrlList.push(file.url)
    }
    const param = {
      cardId: cardInfo.cardId,
      name: cardInfo.name,
      count: cardInfo.count,
      memo: cardInfo.memo,
      imgUrlList: imgUrlList,
    }
    getApp().callContainer('/api/user/card/apply', param, (res) => {
      Notify({ type: 'success', message: '申请成功！', top: this.data.CustomBar });
      this.setData({
        active: "2",
        currStat: 1,
        'qryParam.status': 1
      })
      this.onClearCard();
      this.qryCardApplyList();
    })
  },
  // 查询卡片审核列表
  qryCardApplyList(isNextPage) {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    });
    let isQryNextPage = false;
    if (isNextPage && this.data.cardApplyList.length >= this.data.qryParam.current * this.data.qryParam.size) {
      isQryNextPage = true;
      this.setData({ 'qryParam.current': this.data.qryParam.current + 1 })
    } else if (!isNextPage) {
      this.setData({ 'qryParam.current': 1 })
    }
    getApp().callContainer('/api/user/card/listApply', this.data.qryParam, (res) => {
      if (res.data.data.records && res.data.data.records.length > 0) {
        for (const cardApply of res.data.data.records) {
          cardApply.status_label = cardApplyStat.get(cardApply.status);
          if (isQryNextPage) {
            // 如果查询结果小于查询条数，则下一次不继续分页查询
            if (res.data.data.records.length < this.data.qryParam.size) {
              this.setData({ isQryNextPage: false })
            }
            this.data.cardApplyList.push(cardApply);
          }
        }
      }
      if (isNextPage) {
        this.setData({ cardApplyList: this.data.cardApplyList });
      } else {
        this.setData({ cardApplyList: res.data.data.records || [] });
      }
      this.loadTmpFile();
      Toast.clear();
    }, () => {
      Toast.clear();
    })
  },
  // 缓存图片
  loadTmpFile() {
    for (const cardApply of this.data.cardApplyList) {
      if (!cardApply.imgUrl) {
        continue;
      }
      // 加载卡片图片
      getApp().getTempFilePath(cardApply.imgUrl).then((res) => {
        cardApply.tmpImgUrl = res;
        this.setData({ cardApplyList: this.data.cardApplyList });
      })
    }
  },
  // 卡片申请详情
  onClickCardApply(event) {
    const userCardApplyId = event.currentTarget.dataset.operation;
    wx.navigateTo({
      url: '/pages/user/mycard/apply/detail/detail?userCardApplyId=' + userCardApplyId,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.qryCardTypeList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    if (this.data.active == "2") {
      this.qryCardApplyList()
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})